package com.ysd.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Component
public class RedisCaptcha{
    private static final String CAPTCHA_PREFIX = "captcha:";
    private static RedisTemplate<String, String> redisTemplate;
    private static long expireTime;

    @Autowired
    public RedisCaptcha(RedisTemplate<String, String> redisTemplate) {
        this.redisTemplate = redisTemplate;
        this.expireTime = 20000; // 设置过期时间为20秒
    }

    /**
     * 保存验证码到Redis中
     *
     * @param key     验证码的唯一标识
     * @param captcha 验证码
     */
    public static void saveCaptcha(String key, String captcha) {
        String redisKey = CAPTCHA_PREFIX + key;
        redisTemplate.opsForValue().set(redisKey, captcha, expireTime, TimeUnit.SECONDS);
    }

    /**
     * 获取验证码
     *
     * @param key 验证码的唯一标识
     * @return 验证码
     */
    public static String getCaptcha(String key) {
        String redisKey = CAPTCHA_PREFIX + key;
        return redisTemplate.opsForValue().get(redisKey);
    }

    /**
     * 销毁验证码
     *
     * @param key 验证码的唯一标识
     */
    public static void destroyCaptcha(String key) {
        String redisKey = CAPTCHA_PREFIX + key;
        redisTemplate.delete(redisKey);
    }


}
